<template>
  <div style="width: 600px;height:250px">
    <el-form
      ref="formDynamic"
      size="small"
      :model="formDynamic"
      v-loading="loading"
      :rules="rules"
      class="attrFrom mb20"
      label-width="100px"
      style="min-width: 600px;min-height: 230px;"
      @submit.prevent
    >
      
      <el-row :gutter="24" style="border:1px sold ">
        <el-col :span="10">
          <el-form-item label="规格名称：" label-width="100px" prop="ruleName">
            <el-input maxlength="108" v-model="formDynamic.ruleName" placeholder="请输入标题名称" />
          </el-form-item>
          <!-- <el-button v-if="!isBtn" type="primary" icon="md-add"  @click="addBtn">添加新规格</el-button> -->
          <!-- <el-col :span="24" v-if="isBtn"> -->
          <el-col :span="24">
            <el-form-item label="规格：" label-width="88px">
              <el-input maxlength="120" v-model="attrsName" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="规格值："  label-width="88px">
              <el-input maxlength="120" v-model="attrsVal" placeholder="请输入规格值" />
            </el-form-item>
          </el-col>
          <el-col :span="24" style="display: flex;">
            <el-button type="primary" class="mr10" @click="createAttrName">确定</el-button>
            <el-button @click="offAttrName">取消</el-button>
          </el-col>
        </el-col>
        <el-col :span="14"  v-for="(item, index) in formDynamic.ruleValue" :key="index" class="noForm">
          <el-form-item>
            <div class="acea-row row-middle">
              <span class="mr5">{{ item.value }}</span
              ><i class="el-icon-circle-close" @click="handleRemove(index)" />
            </div>
            <div>
              <el-tag
                v-for="(j, indexn) in item.detail"
                :key="indexn"
                closable
                size="default"
                style="padding: 5px;"
                :disable-transitions="false"
                @close="handleClose(item.detail, indexn)"
              >
                {{ j }}
              </el-tag>
              <!-- <el-input
                v-if="item.inputVisible"
                ref="saveTagInput"
                v-model="item.detail.attrsVal"
                class="input-new-tag"
                size="small"
                style="padding-left: 5px;"
                @keyup.enter="createAttr(item.detail.attrsVal, index)"
                @blur="createAttr(item.detail.attrsVal, index)"
              /> -->
              <!-- <el-button v-else class="button-new-tag" size="small" @click="showInput(item)">+ 添加</el-button> -->
            </div>
          </el-form-item>
        </el-col>
        
        <!-- <el-col :span="8"  style="padding-left: 0; padding-right: 0;display: grid;">
          
        </el-col> -->
        <!-- <Spin v-if="spinShow" size="large" fix /> -->
      </el-row>
      
      <template v-slot:footer>
        <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
      </template>
     
    </el-form>
    <span style="display:flex">
      <el-button @click="resetForm('formDynamic')">取消</el-button>
      <el-button type="primary" :loading="loadingBtn" @click="handleSubmit('formDynamic')">确 定</el-button>
    </span>
  </div>
</template>

<script>
import { attrCreatApi, attrEditApi } from '@/api/shopping/store';
export default {
  name: 'CreatAttr',
  props: {
    currentRow: {
      type: Object,
      default: null,
    },
    keyNum: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      loadingBtn: false,
      loading: false,
      dialogVisible: false,
      inputVisible: false,
      inputValue: '',
      spinShow: false,
      grid: {
        xl: 3,
        lg: 3,
        md: 12,
        sm: 24,
        xs: 24,
      },
      modal: false,
      index: 1,
      rules: {
        ruleName: [{ required: true, message: '请输入规格名称', trigger: 'blur' }],
      },
      formDynamic: {
        ruleName: '',
        ruleValue: [],
      },
      attrsName: '',
      attrsVal: '',
      isBtn: false,
      results: [],
      result: [],
      ids: 0,
    };
  },
  watch: {
    currentRow: {
      handler: function (val, oldVal) {
        if (val) { 
          this.formDynamic = val;
        }
      },
      immediate: true,
    },
    keyNum: {
      deep: true,
      handler(val) {
        if (val > 0) this.clear();
      },
    },
  },
  mounted() {
    // this.formDynamic.ruleValue.map((item) => {
    //   this.$set(item, 'inputVisible', false);
    // });
  },
  methods: {
    resetForm(formName) {
      this.clear();
      this.$refs[formName].resetFields();
    },
    // 添加按钮
    addBtn() {
      this.isBtn = true;
    },
    handleClose(item, index) {
      item.splice(index, 1);
    },
    // 取消
    offAttrName() {
      this.isBtn = false;
    },
    // 删除
    handleRemove(index) {
      this.formDynamic.ruleValue.splice(index, 1);
    },
    // 添加规则名称
    createAttrName() {
      if (this.attrsName && this.attrsVal) {
        const data = {
          value: this.x,
          detail: [this.attrsVal],
        };
        this.formDynamic.ruleValue.push(data);
        var hash = {};
        this.formDynamic.ruleValue = this.formDynamic.ruleValue.reduce(function (item, next) {
          hash[next.value] ? '' : (hash[next.value] = true && item.push(next));
          return item;
        }, []);
        this.attrsName = '';
        this.attrsVal = '';
        this.isBtn = false;
      } else {
        ElMessage({ message: '请先添加规格名称', type: 'warning',})
      }
    },
    // 添加属性
    createAttr(num, idx) {
      if (num) {
        this.formDynamic.ruleValue[idx].detail.push(num);
        var hash = {};
        this.formDynamic.ruleValue[idx].detail = this.formDynamic.ruleValue[idx].detail.reduce(function (item, next) {
          hash[next] ? '' : (hash[next] = true && item.push(next));
          return item;
        }, []);
        this.formDynamic.ruleValue[idx].inputVisible = false;
      } else {
        ElMessage({ message: '请添加属性', type: 'warning',})
      }
    },
    showInput(item) {
      this.$set(item, 'inputVisible', true);
    },
    // 提交
    handleSubmit(name) {
      const data = {
        id: this.currentRow.id || 0,
        ruleName: this.formDynamic.ruleName,
        ruleValue: JSON.stringify(this.formDynamic.ruleValue),
      };
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.formDynamic.ruleValue.length === 0) {
            ElMessage({ message: '请至少添加一条属性规格！', type: 'warning',})
            return;
          }
          this.loadingBtn = true;
          this.loading = true;
          setTimeout(() => {
            this.currentRow.id
              ? attrEditApi(data)
                .then((res) => {
                  ElMessage({ message: '提交成功', type: 'success',})
                    this.clear();
                    this.$emit('getList');
                    this.loading = false;
                    this.loadingBtn = false;
                  })
                  .catch(() => {
                    this.loading = false;
                    this.loadingBtn = false;
                  })
              : attrCreatApi(data)
                  .then((res) => {
                    ElMessage({ message: '提交成功', type: 'success',})
                    this.$emit('getList');
                    this.clear();
                    this.loading = false;
                    this.loadingBtn = false;
                  })
                  .catch(() => {
                    this.loading = false;
                    this.loadingBtn = false;
                  });
          }, 1200);
        } else {
          this.loading = false;
          this.loadingBtn = false;
          return false;
        }
      });
    },
    clear() {
      this.$refs['formDynamic'].resetFields();
      this.formDynamic.ruleValue = [];
      this.formDynamic.ruleName = '';
      this.isBtn = false;
      this.attrsName = '';
      this.attrsVal = '';
    },
    handleInputConfirm() {
      const inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
  },
};
</script>

<style scoped lang="scss">
</style>
